from views.gallery_view import GalleryView
import customtkinter as ctk
from tkinter import filedialog, messagebox
import shutil
import os

class FavoritesGalleryView(GalleryView):
    def __init__(self, parent, image_files, thumbnail_size=(100, 100), select_callback=None):
        super().__init__(parent, image_files, thumbnail_size, select_callback)
        self.current_page = 1  # 确保初始页码为1

    def create_gallery_view(self):
        super().create_gallery_view()

        # 添加导出按钮
        self.export_button = ctk.CTkButton(
            self.pagination_frame,
            text="导出全部收藏",
            command=self.export_favorites
        )
        self.export_button.pack(side="right", padx=5)

    def update_gallery(self):
        # 获取主应用程序实例
        root = self.master.winfo_toplevel()
        self.image_files = list(root.favorites)
        super().update_gallery()

        # 根据是否有收藏图片，启用或禁用导出按钮
        if self.image_files:
            self.export_button.configure(state="normal")
        else:
            self.export_button.configure(state="disabled")

    def export_favorites(self):
        # 打开文件夹选择对话框
        export_directory = filedialog.askdirectory(title="选择导出目录")
        if not export_directory:
            return  # 用户取消操作

        # 复制所有收藏的图片到选定的文件夹
        exported_count = 0
        for favorite in self.image_files:
            if os.path.isfile(favorite):
                filename = os.path.basename(favorite)
                destination = os.path.join(export_directory, filename)
                try:
                    shutil.copy2(favorite, destination)
                    exported_count += 1
                except Exception as e:
                    messagebox.showerror(
                        "导出错误",
                        f"复制 {filename} 失败：\n{e}"
                    )

        messagebox.showinfo(
            "导出完成",
            f"已导出 {exported_count} 张收藏的图片到：\n{export_directory}"
        )
